/**
 * Created by ACER on 2017/4/14.
 */
app.controller('search', function ($scope, $http) {
    var searchInfo = sessionStorage.getItem('searchInfo');
    var typeIdSrt = sessionStorage.getItem('typeid');
    var typeId = parseInt(typeIdSrt);

    // 当前获取的任务页
    $scope.page = 1;

    // 默认当前不处于加载更多页面的状态
    $scope.isOnloading = false;

    // 获取的任务列表
    $scope.taskList = [];

    // 指定的价格区间
    $scope.conditionPrice = {
        maxPrice: null,
        minPrice: null
    };


    // 指定的距离
    $scope.distanceChose = 1000;

    // 指定关键词
    $scope.keyword = null;
    // 指定的任务类型
    $scope.taskType = null;
    if (searchInfo) {
        $scope.keyword = searchInfo;
    }
    if (typeId) {
        $scope.taskType = typeId;
    }



    // 默认筛选条件
    $scope.condition = {
        taskType: $scope.taskType,
        maxPrice: $scope.conditionPrice.maxPrice,
        minPrice: $scope.conditionPrice.minPrice,
        x: null,
        y: null,
        distance: $scope.distanceChose,
        keyword: $scope.keyword
    };


    // 所有应有的类型范围，默认所有
    $scope.types = [{
        taskTypeId: null,
        taskTypeName: '所有'
    }];

    // 所有的距离选择范围，默认1km
    $scope.distanceList = [
        {
            distanceDescribe: '<1km',
            distance: 1000
        },
        {
            distanceDescribe: '<2km',
            distance: 2000
        },
        {
            distanceDescribe: '<3km',
            distance: 3000
        },
        {
            distanceDescribe: '<5km',
            distance: 5000
        },
        {
            distanceDescribe: '<7.5km',
            distance: 7500
        },
        {
            distanceDescribe: '<10km',
            distance: 10000
        },
        {
            distanceDescribe: '<100km',
            distance: 100000
        },
        {
            distanceDescribe: '<200km',
            distance: 200000
        }
    ];


    // 页面初始化
    $scope.pageInit = function () {
        // 获取任务类型
        $scope.getTaskType();

        // 获取默认任务列表
        $scope.search();

        // 注册监听事件
        $scope.watchAll();

    };

    $scope.watchAll = function () {
        $scope.$watch('conditionPrice', function () {
            if ($scope.condition.maxPrice == $scope.conditionPrice.maxPrice &&
                $scope.condition.minPrice == $scope.conditionPrice.minPrice) {
                return;
            }
            $scope.condition.maxPrice = $scope.conditionPrice.maxPrice;
            $scope.condition.minPrice = $scope.conditionPrice.minPrice;
        }, true);

        $scope.$watch('distanceChose', function () {
            if ($scope.condition.distance == $scope.distanceChose) {
                return;
            }
            $scope.condition.distance = $scope.distanceChose;
            // 刷新（重新获取）
            $scope.search();
        });

        $scope.$watch('keyword', function () {
            $scope.condition.keyword = $scope.keyword;
        });

        $scope.$watch('taskType', function () {
            if ($scope.condition.taskType == $scope.taskType) {
                return;
            }
            $scope.condition.taskType = $scope.taskType;
            // 刷新（重新获取）
            $scope.search();
        });
    };

    $scope.getTaskType = function () {
        $http({
            method: 'get',
            url: app.netPath + '/tasks/showAllTaskType'
        }).then(function (res) {
            if (!res.data.error) {
                var types = res.data.data;
                for (var i = 0; i < types.length; i++) {
                    $scope.types.push(types[i]);
                }
                if (typeId) {
                    $scope.taskType = typeId;
                    sessionStorage.removeItem('typeid');
                }
            } else {

                switch (res.data.error) {
                    case 100:
                        $scope.errorInfo = '定位失败';
                        break;
                    case 110:
                        $scope.errorInfo = '找不到内容';
                        break;
                    case 200:
                        $scope.errorInfo = '请求异常';
                        break;
                    default :
                        $scope.errorInfo;
                }

            }
        }, function () {
            $.alert('网络出错');
        })
    };


    $scope.search = function (page) {

        var token = localStorage.getItem('token');
        if (!token) {
            token = null
        }

        // 准备工作
        if (!app.isPlusReady || !app.addressInfo) {
            $.alert('不能获取到当前位置，无法检索');
            return;
        }
        $scope.condition.x = app.addressInfo.coords.latitude;
        $scope.condition.y = app.addressInfo.coords.longitude;
        // $scope.condition.x = 30.58178;
        // $scope.condition.y = 104.277946;
        $scope.condition.page = page ? page : 1;

        // 若该加载为初始化加载，即没有传入page参数
        if (!page) {
            $scope.taskList = [];
            $scope.page = 1;
        }


        $.showPreloader('获取中');
        $http({
            method: 'get',
            //method:'get',
            headers: {Authorization: token},
            url: app.netPath + '/tasks/search/classification',
            params: $scope.condition
        }).then(
            function (res) {
                if (!res.data.error) {
                    var taskList = res.data.data;
                    for (var i = 0; i < taskList.length; i++) {
                        var lat = taskList[i].taskPosition.positionX;
                        var lng = taskList[i].taskPosition.positonY;
                        taskList[i].distance = app.getGreatCircleDistance(lat, lng);
                        $scope.taskList.push(taskList[i]);
                        //console.log($scope.taskList.length);
                        //console.log(lat);
                        //console.log(lng);
                        //console.log(app.getGreatCircleDistance(lat, lng));
                    }

                    var infiniteScroll = $('.infinite-scroll');
                    var infiniteScrollPreloader = $('.infinite-scroll-preloader');
                    // 启用无限加载事件
                    $.attachInfiniteScroll(infiniteScroll);
                    // 启用提示符
                    infiniteScrollPreloader.show();
                    if (res.data.allPage <= $scope.condition.page) {
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        $.detachInfiniteScroll(infiniteScroll);
                        // 删除加载提示符
                        infiniteScrollPreloader.hide();
                    }
                } else {
                    console.log(res.data.msg);
                }
                $scope.isOnloading = false;
                $.hidePreloader();
            },
            function () {
                $.alert('网络出错');
                $.hidePreloader();
                $scope.isOnloading = false;
            }
        )
    };


    $scope.getSearchTaskId = function (taskhomeid) {
        sessionStorage.setItem('taskhomeid', taskhomeid);
        location.href = '#others-task-details';
    };

    // 选择金额区间
    $scope.chooseMoney = function () {
        var popup = $('.popup-overlay');
        $.popup('.popup-money');
    }

});